package com.chagee.store.operation.server.event.mq.producer;

import com.alibaba.fastjson.JSON;
import com.chagee.store.operation.api.enums.ForewarningTypeEnum;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.server.hadler.StoreIssueNotice;
import java.util.Objects;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * 工单AI分析异常通知发消息给iot
 * topic: store_issue_notice
 *
 * @Author : hk
 * @Date : 2024/5/14
 */
@Slf4j
@Service
public class MqMessageService {

	@Resource(name = "oldRocketMQTemplate")
	private RocketMQTemplate oldRocketMQTemplate;
	@Resource(name = "rocketMQTemplate")
	private RocketMQTemplate rocketMQTemplate;

	/**
	 * 发送mq消息
	 *
	 * @param body
	 * @return
	 */
	public boolean sendMessage(StoreIssueNotice body) {
		log.info("topic: {},send_mq_message: {}", CommonConstant.ACCEPTANCE_FOREWARNING_TOPIC, JSON.toJSONString(body));
		ForewarningTypeEnum changeTypeEnum = ForewarningTypeEnum.queryByType(body.getIssueType());
		if (Objects.isNull(changeTypeEnum)) {
			throw new BizException(BizErrorCode.REQUEST_VALID_FAILED);
		}
//		if (Objects.isNull(storeDO)) {
//			throw new BizException(BizErrorCode.STORE_NOT_EXIST);
//		}
		SendStatus oldSendResultStatus = null;
		SendStatus newSendResultStatus = null;
		try {
			SendResult sendResult = oldRocketMQTemplate.syncSend(CommonConstant.ACCEPTANCE_FOREWARNING_TOPIC, MessageBuilder.withPayload(body).build());
			log.info("old_MQ_message_send_result:{}", JSON.toJSONString(sendResult));
			oldSendResultStatus = sendResult.getSendStatus();
		} catch (Exception e) {
			log.error("old_send_mq_message_topic:{}, body:{}", CommonConstant.ACCEPTANCE_FOREWARNING_TOPIC, JSON.toJSONString(body), e);
		}
		try {
			SendResult newSendResult = rocketMQTemplate.syncSend(CommonConstant.ACCEPTANCE_FOREWARNING_TOPIC, MessageBuilder.withPayload(body).build());
			log.info("MQ_message_send_result:{}", JSON.toJSONString(newSendResult));
			newSendResultStatus = newSendResult.getSendStatus();
		} catch (Exception e) {
			log.error("old_send_mq_message_topic:{}, body:{}", CommonConstant.ACCEPTANCE_FOREWARNING_TOPIC, JSON.toJSONString(body), e);
		}

		return SendStatus.SEND_OK.equals(oldSendResultStatus) && SendStatus.SEND_OK.equals(newSendResultStatus);
	}
}
